<template>
  <div>
    <el-card>
      <template #header>
        <h2>膳食日历</h2>
      </template>

      <!-- 星期选择 -->
      <el-form :model="filter" inline>
        <el-form-item label="星期">
          <el-radio-group v-model="filter.dayOfWeek">
            <el-radio-button v-for="(label, idx) in days" :key="idx" :label="idx+1">
              {{ label }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <!-- 早餐 / 午餐 / 晚餐 三行展示 -->
      <div v-for="(mealLabel, mealType) in meals" :key="mealType" class="meal-row">
        <h3>{{ mealLabel }}</h3>
        <div class="dish-list">
          <div
            v-for="item in calendar[mealType]"
            :key="item.id"
            class="dish-card"
          >
            <div class="img-wrapper">
              <img :src="item.imageUrl" alt="" />
              <div class="tag">{{ tastes[item.taste] }}</div>
            </div>
            <div class="info">
              <div class="name">{{ item.name }}</div>
              <div class="meta">类目: {{ categories[item.category] }}</div>
              <div class="meta">¥{{ item.price.toFixed(2) }}</div>
            </div>
			<div class="actions">
				<!-- 修改图标 -->
				<el-icon
				  class="icon-btn"
				  @click="openEditor(item, mealType)"
				  title="修改"
				>
				  <Edit />
				</el-icon>
				<!-- 删除图标 -->
				<el-icon
				  class="icon-btn"
				  @click="onDelete(item.id)"
				  title="删除"
				>
				  <Delete />
				</el-icon>
			  </div>
          </div>

          <!-- 新增卡片 -->
          <div class="dish-card add-card" @click="openEditor(null, mealType)">
            <span>＋ 添加</span>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 编辑/新增 弹窗 -->
   <el-dialog :title="editorTitle" v-model="editorVisible">
       <el-form :model="editorForm" label-width="80px">
         <el-form-item label="菜品">
           <el-select
             v-model="editorForm.dishId"
             placeholder="请选择菜品"
             filterable
           >
             <el-option
               v-for="d in allDishes"
               :key="d.id"
               :label="d.name"
               :value="d.id"
             >
              
             </el-option>
           </el-select>
         </el-form-item>
         <el-form-item label="口味">
           <el-select v-model="editorForm.taste" placeholder="请选择口味">
             <el-option v-for="(t, v) in tastes" :key="v" :label="t" :value="v" />
           </el-select>
         </el-form-item>
       </el-form>
       <template #footer>
         <el-button @click="editorVisible = false">取消</el-button>
         <el-button type="primary" @click="onSave">保存</el-button>
       </template>
     </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, inject, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Delete } from '@element-plus/icons-vue'
import qs from 'qs'
const axios = inject('axios')


// 星期、餐次、口味、分类映射
const days = ['周一','周二','周三','周四','周五','周六','周日']
const meals = { 1:'早餐',2:'午餐',3:'晚餐' }
const tastes = { 1:'多盐',2:'少盐',3:'清淡',4:'原味' }
const categories = { 1:'主食',2:'汤羹',3:'热菜',4:'凉菜',5:'甜点' }

// 过滤条件
const filter = reactive({ dayOfWeek:1 })

// 日历数据：calendar[mealType] = [{…DietCalendarDTO + Dish…}, …]
const calendar = reactive({ 1:[], 2:[], 3:[] })

// 所有菜品下拉列表
const allDishes = ref([])

// 编辑器
const editorVisible = ref(false)
const editorTitle = ref('新增')
const editorForm = reactive({
  id: null,           // DietCalendar.id
  dishId: null,
  taste: 1,
  dayOfWeek: 1,
  mealType: 1
})

// 加载所有菜品
async function loadDishes(){
  const r = await axios.get('DishController/queryDish')
  if(r.data.status===200) allDishes.value = r.data.data
}

// 加载日历
async function loadCalendar(){
  for(const mt of [1,2,3]){
    const resp = await axios.post(
      'DietCalendarController/queryDietCalendar',
      qs.stringify({ dayOfWeek: filter.dayOfWeek, mealType: mt })
    )
    const rb = resp.data
    if (rb.status === 200) {
      calendar[mt] = rb.data
    } else {
      calendar[mt] = []
      ElMessage.warning(`加载${meals[mt]}失败：` + rb.message)
    }
  }
}

// 打开编辑/新增
function openEditor(item, mealType){
  if(item){
    editorTitle.value = '修改'
    Object.assign(editorForm, {
      id:           item.id,
      dishId:       item.dishId,
      taste:        item.taste,
      dayOfWeek:    item.dayOfWeek,
      mealType
    })
  } else {
    editorTitle.value = '新增'
    Object.assign(editorForm, {
      id:           null,
      dishId:       null,
      taste:        1,
      dayOfWeek:    filter.dayOfWeek,
      mealType
    })
  }
  editorVisible.value = true
}

// 保存
async function onSave(){
  const api = editorForm.id ? 'DietCalendarController/updateDietCalendar' : 'DietCalendarController/addDietCalendar'
  const r = await axios.post(api, qs.stringify(editorForm))
  if(r.data.status===200){
    ElMessage.success('保存成功')
    editorVisible.value = false
    loadCalendar()
  } else {
    ElMessage.error('保存失败：'+r.data.message)
  }
}

// 删除
async function onDelete(id){
  await ElMessageBox.confirm('确认删除？','警告',{ type:'warning' })
  const r = await axios.post('DietCalendarController/deleteDietCalendar', qs.stringify({ id }))
  if(r.data.status===200){
    ElMessage.success('删除成功')
    loadCalendar()
  } else {
    ElMessage.error('删除失败：'+r.data.message)
  }
}

// 初始化
onMounted(()=>{
  loadDishes()
  loadCalendar()
})

// 监听星期变化，重新拉数据
watch(() => filter.dayOfWeek, () => {
  loadCalendar()
})

</script>

<style scoped>
.meal-row { margin-top: 24px; }
.dish-list { display: flex; gap:16px; flex-wrap: wrap; }
.dish-card {
  width: 140px;
  border: 1px solid #eee;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
}
.img-wrapper {
  position: relative;
  height: 100px;
  background: #fafafa;
}
.img-wrapper img { width: 100%; height: 100%; object-fit: cover; }
.img-wrapper .tag {
  position: absolute; top:4px; left:4px;
  background: rgba(0,0,0,0.6); color:#fff; padding:2px 4px; font-size:12px;
  border-radius:2px;
}
.info { padding:8px; font-size: 12px; }
.info .name { font-weight: bold; margin-bottom:4px; }
.actions {
  position: absolute;
  top: 4px;
  right: 4px;
  display: flex;
  gap: 4px;
}
.icon-btn {
  font-size: 16px;
  cursor: pointer;
  color: rgba(0,0,0,0.6);
  transition: color .2s;
}
.icon-btn:hover {
  color: #409EFF; /* Element primary color */
}
.add-card {
  display:flex; align-items:center; justify-content: center;
  color: #888; font-size: 24px; cursor: pointer;
  border: 2px dashed #ddd;
}
</style>
